package slavik.voloshyn.vashmagazyn;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;

public class CustomMap<CustomVector, Announcement> extends
        HashMap<CustomVector, Announcement>
{
	private final static int DISCOVERED_IN_BLACKLIST = 0;
	private final static int DISCOVERED_IN_MAP = 1;
	private final static int NOT_DISCOVERED = 3;
	private final HashSet<String> blackList = new HashSet<String>();

	@Override
	public Announcement put(CustomVector arg0, Announcement arg1)
	{
		if (containsKey(arg0))
		{
			return null;
		}
		System.out.println("added:" + arg0);
		return super.put(arg0, arg1);
	}

	private String[] getTokens(CustomVector customVector)
	{
		StringTokenizer stringTokenizer = new StringTokenizer(
		        customVector.toString(), ",");
		String[] keys = new String[stringTokenizer.countTokens()];
		for (int i = 0; i <= stringTokenizer.countTokens(); i++)
		{
			keys[i] = stringTokenizer.nextToken();
			// System.out.println(keys[i]);
		}
		return keys;
	}

	@Override
	public boolean containsKey(Object keys)
	{
		String[] argumentKeys = getTokens((CustomVector) keys);
		for (Iterator<CustomVector> iterator = this.keySet().iterator(); iterator
		        .hasNext();)
		{
			CustomVector tempKey = iterator.next();
			String[] currentKeys = getTokens(tempKey);

			switch (checkKeys(argumentKeys, currentKeys))
			{
				case DISCOVERED_IN_BLACKLIST:
				{
					System.out.println("dublicated:" + keys.toString());
					return true;
				}
				case DISCOVERED_IN_MAP:
				{
					System.out.println("deleted:" + tempKey.toString());
					remove(tempKey);
					return true;
				}
				case NOT_DISCOVERED:
				{
					continue;
				}
			}
		}
		return false;

	}

	private int checkKeys(String[] keys1, String[] keys2)
	{
		for (String key1 : keys1)
		{
			if (blackList.contains(key1))
			{
				blackList.addAll(Arrays.asList(keys1));
				return DISCOVERED_IN_BLACKLIST;
			}
			for (String key2 : keys2)
			{
				if (key1.contentEquals(key2))
				{
					blackList.addAll(Arrays.asList(keys1));
					blackList.addAll(Arrays.asList(keys2));
					return DISCOVERED_IN_MAP;
				}
			}
		}
		return NOT_DISCOVERED;
	}
}
